package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Resource
    ApUserMapper mapper;

    @Override
    public ResponseResult loginAuth(LoginDTO dto) {
        if (dto==null || dto.getEquipmentId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            ApUser apUser = mapper.selectOne(new LambdaQueryWrapper<ApUser>().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null){
                CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            String password = apUser.getPassword();
            String salt = apUser.getSalt();
            String encodeWithSalt = MD5Utils.encodeWithSalt(dto.getPassword(), salt);
            if (!encodeWithSalt.equals(password)){
                log.error("密码错误，password：{} salt：{} encodeWithSalt：{} dto.getPassword()：{}",password,salt,encodeWithSalt,dto.getPassword());
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
